package com.atguigu.srb.core.service.impl;

import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.core.enums.BorrowInfoStatusEnum;
import com.atguigu.srb.core.enums.BorrowerStatusEnum;
import com.atguigu.srb.core.enums.UserBindEnum;
import com.atguigu.srb.core.mapper.*;
import com.atguigu.srb.core.pojo.entity.*;
import com.atguigu.srb.core.pojo.vo.BorrowInfoApprovalVO;
import com.atguigu.srb.core.pojo.vo.BorrowerDetailVO;
import com.atguigu.srb.core.service.BorrowInfoService;
import com.atguigu.srb.core.service.BorrowerService;
import com.atguigu.srb.core.service.DictService;
import com.atguigu.srb.core.service.LendService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author tjf
 * @since 2022-01-03
 */
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private IntegralGradeMapper integralGradeMapper;
    @Resource
    private BorrowerMapper borrowerMapper;

    private final DictService dictService;
    private final BorrowerService borrowerService;
    private final LendService lendService;

    public BorrowInfoServiceImpl(DictService dictService, BorrowerService borrowerService, LendService lendService) {
        this.dictService = dictService;
        this.borrowerService = borrowerService;
        this.lendService = lendService;
    }

    @Override
    public BigDecimal getBorrowAmount(Long userId) {
        // 获取用户积分
        LambdaQueryWrapper<UserInfo> userInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userInfoLambdaQueryWrapper.select(UserInfo::getIntegral)
                .eq(UserInfo::getId, userId);
        List<Object> objects = userInfoMapper.selectObjs(userInfoLambdaQueryWrapper);
        Assert.isTrue(objects.size() == 1, ResponseEnum.LOGIN_MOBILE_ERROR);
        Integer integral = (Integer) objects.get(0);

        // 查询借款额度
        LambdaQueryWrapper<IntegralGrade> integralGradeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        integralGradeLambdaQueryWrapper.select(IntegralGrade::getBorrowAmount)
                .gt(IntegralGrade::getIntegralEnd, integral)
                .le(IntegralGrade::getIntegralStart, integral);
        List<Object> borrowAmountList = integralGradeMapper.selectObjs(integralGradeLambdaQueryWrapper);
        Assert.isTrue(borrowAmountList.size() < 2, ResponseEnum.ERROR);
        if (borrowAmountList.size() == 0) {
            return new BigDecimal("0");
        }
        return (BigDecimal) borrowAmountList.get(0);
    }

    @Override
    public void saveBorrowInfo(Long userId, BorrowInfo borrowInfo) {
        // 判断用户绑定和审批状态
        UserInfo userInfo = userInfoMapper.selectById(userId);
        Assert.equals(UserBindEnum.BIND_OK.getStatus(), userInfo.getBindStatus(), ResponseEnum.USER_NO_BIND_ERROR);
        Assert.equals(BorrowerStatusEnum.AUTH_OK.getStatus(), userInfo.getBorrowAuthStatus(), ResponseEnum.USER_NO_AMOUNT_ERROR);

        // 判断借款人额度是否充足
        BigDecimal borrowAmount = this.getBorrowAmount(userId);
        Assert.isTrue(borrowInfo.getAmount().doubleValue() <= borrowAmount.doubleValue(), ResponseEnum.USER_AMOUNT_LESS_ERROR);

        // 存borrowInfo数据
        borrowInfo.setUserId(userId);
        // 百分比转小数
        borrowInfo.setBorrowYearRate(borrowInfo.getBorrowYearRate().divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        // 设置借款申请的审核状态
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());
        baseMapper.insert(borrowInfo);
    }

    @Override
    public Integer getStatusByUserId(Long userId) {
        LambdaQueryWrapper<BorrowInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(BorrowInfo::getStatus).eq(BorrowInfo::getUserId, userId);
        List<Object> objects = baseMapper.selectObjs(queryWrapper);
        if (objects.size() == 0) {
            return BorrowInfoStatusEnum.NO_AUTH.getStatus();
        }
        return (Integer) objects.get(0);
    }

    @Override
    public List<BorrowInfo> selectList() {
        List<BorrowInfo> borrowInfoList = baseMapper.selectBorrowInfoList();
        borrowInfoList.forEach(borrowInfo -> {
            String returnMethod = dictService.getNameByParentDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
            String moneyUse = dictService.getNameByParentDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
            String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());
            borrowInfo.getParam().put("returnMethod", returnMethod);
            borrowInfo.getParam().put("moneyUse", moneyUse);
            borrowInfo.getParam().put("status", status);
        });
        return borrowInfoList;
    }

    @Override
    public Map<String, Object> getBorrowInfoDetail(Long id) {
        // 获取borrowInfo
        BorrowInfo borrowInfo = baseMapper.selectById(id);
        String returnMethod = dictService.getNameByParentDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
        String moneyUse = dictService.getNameByParentDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
        String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());
        borrowInfo.getParam().put("returnMethod", returnMethod);
        borrowInfo.getParam().put("moneyUse", moneyUse);
        borrowInfo.getParam().put("status", status);

        // 获取borrowerVO
        LambdaQueryWrapper<Borrower> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Borrower::getUserId, borrowInfo.getUserId());
        Borrower borrower = borrowerMapper.selectOne(queryWrapper);
        BorrowerDetailVO borrowerDetailVO = borrowerService.getBorrowerDetailVOById(borrower.getId());

        // 组装返回的map
        HashMap<String, Object> map = new HashMap<>();
        map.put("borrowInfo", borrowInfo);
        map.put("borrower", borrowerDetailVO);
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void approval(BorrowInfoApprovalVO borrowInfoApprovalVO) {
        // 修改借款信息表状态
        BorrowInfo borrowInfo = baseMapper.selectById(borrowInfoApprovalVO.getId());
        Assert.notNull(borrowInfo, ResponseEnum.ERROR);
        borrowInfo.setStatus(borrowInfoApprovalVO.getStatus());
        baseMapper.updateById(borrowInfo);

        //增加lend标定表记录
        if (borrowInfoApprovalVO.getStatus().intValue() == BorrowInfoStatusEnum.CHECK_OK.getStatus().intValue()) {
            lendService.createLend(borrowInfoApprovalVO, borrowInfo);
        }
    }
}
